#!/usr/bin/env python
# encoding: utf-8
'''
@author: Excelsiorly
@license: (C) Copyright 2022, All Rights Reserved.
@contact: excelsiorly@qq.com
@file: 206. 反转链表.py
@time: 2022/1/5 13:32
@desc: https://leetcode-cn.com/problems/reverse-linked-list/
给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。
@解题思路：
    1. 迭代，双指针（实际上是三指针，只不过python隐藏细节罢了）
        - 每次都将当前结点的下一结点（next结点）存起来
        - 接着将当前结点的next指针指向前驱结点pre
        - 然后更新前驱结点为当前结点p
        - 更新当前结点到第一步保存的next结点
        - Ot(n), Os(1)
'''
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def reverseList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        pre, p = None, head
        while p:
            next = p.next
            p.next = pre
            pre = p
            p = next
        return pre